#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
#define THREAD_ERROR_CHECK(ret, msg)                       \
    {                                                      \
        if (ret != 0)                                      \
        {                                                  \
            fprintf(stderr % s : % s, msg, strerror(ret)); \
        }                                                  \
    }
#define ARGS_CHECK(argc, num)               \
    {                                       \
        if (argc != num)                    \
        {                                   \
            fprintf(stderr, args error !n); \
            return -1;                      \
        }                                   \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
int main(int argc, char *argv[])
{
    int fdw = open("chat1.pipe", O_WRONLY);
    ERROR_CHECK(-1, fdw, "open chart2");
    int fdr = open("chat2.pipe", O_RDONLY);
    ERROR_CHECK(-1, fdr, "open chart1");

    puts("pipe open");
    char buf[1024] = {0};
  
    fd_set rw_set;
    while (1)
    {
        FD_ZERO(&rw_set);
        FD_SET(STDIN_FILENO, &rw_set);
        FD_SET(fdr, &rw_set);
        struct timeval timeout;
        timeout.tv_sec = 20;
        timeout.tv_usec = 0;
        int ret = select(fdr + 1, &rw_set, NULL, NULL, &timeout);
        if (FD_ISSET(fdr, &rw_set))
        {
            puts("msg from pipe");
            memset(buf, 0, sizeof(buf));
            int ret = read(fdr, buf, sizeof(buf));
             if (strncmp(buf, "quit", 4) == 0)
            {
               
                puts("quit");
                close(fdr);
                close(fdw);
                  return 0;

            }
            puts(buf);
        }
        if (FD_ISSET(STDIN_FILENO, &rw_set))
        {
            puts("msg from stdin");
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            write(fdw, buf, strlen(buf));
               if (strncmp(buf, "quit", 4) == 0)
            {
               
                puts("end");
                close(fdr);
                close(fdw);
                 return 0;

            }
        }
        if (ret == 0)
        {
            puts("timeout");
            continue;
        }
    }

    return 0;
}